const config = require('../../utils/config.js')
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
const toast = require('../../utils/toast.js');
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // baseinfo
    ysId: undefined,
    ysType: undefined,
    //队友
    professionType: ['不限', '哲学', '经济学', '法学', '教育学', '文学', '历史学', '理学', '工学', '农学', '医学', '军事学', '管理学和艺术学'],
    education: ['不限', '本科', '大专', '博士', '高中', '博士后'],
    grade: ['不限', '一年级', '二年级', '三年级', '四年级', '五年级'],
    province: ['不限', '北京市', '天津市', '上海市', '重庆市', '河北省', '山西省', '辽宁省', '吉林省', '黑龙江省', '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省', '河南省', '湖北省', '湖南省', '广东省', '海南省', '四川省', '贵州省', '云南省', '陕西省', '甘肃省', '青海省', '台湾省', '内蒙古自治区', '广西壮族自治区', '西藏自治区', '宁夏回族自治区', '新疆维吾尔自治区', '香港特别行政区', '澳门特别行政区'],

    editType: '',
    // team
    teamList: [],
    modalName: "",
    formData: { name: "", maxNum: 5 },
    shareData: {}, //分享设置
    // yisai
    tabCur: 0,
    tabItems: ["组队", "竞赛介绍"],
    // post
    post: {},
    isShow: false,
    collection: { status: false, text: "收藏", icon: "favor" },
    zan: { status: false, text: "点赞", icon: "appreciate" },
    showLogin: false,
    userInfo: {},
    commentContent: "",
    commentPage: 1,
    commentList: [],
    nomore: false,
    nodata: false,
    commentId: "",
    placeholder: "评论...",
    focus: false,
    toName: "",
    toOpenId: "",
    nodata_str: "暂无评论，赶紧抢沙发吧",
    isShowPosterModal: false,//是否展示海报弹窗
    posterImageUrl: "",//海报地址
    showBanner: false,
    showBannerId: "",
    hideArticle: ''//400rpx
  },
  /**
    * 生命周期函数--监听页面显示
    */
  onShow: function (option) {
    let editType = this.data.editType;
    //学校编辑
    let school = this.data.changeSchool;
    if (editType == 'school' && school) {
      this.changeForm('school_name', school.name)
      this.changeForm('school_id', school.id)
    }
    //技能
    let skill = this.data.skills_good;
    if (editType == 'good' && skill) {
      this.changeForm('skills_good', skill);
    }
  },
  // team
  onInputTeamName(event) {
    const { value } = event.detail
    this.changeForm('teamName', value)
  },
  onCreateTeam() {
    if (!this.data.formData.name || !this.data.formData.maxNum) {
      return
    }
    let formData = this.data.formData
    formData.ysType = this.data.ysType
    formData.ysId = this.data.ysId

    // post data
    api.request.post('/team/add', formData).then((res) => {
      console.log("api.addTeam", res)
      this.hideModal()
    })
  },
  onShowCreateTeamModel(e) {
    this.showSelectModal('createTeamModel')
  },
  onShowFindStuModel(e) {
    this.showSelectModal('findStuModel')
  },
  onShowFindTeamModel(e) {
    this.showSelectModal('findTeamModel')
  },
  showSelectModal(name) {
    this.setData({
      modalName: name,
      formData: {}
    })

  },
  hideModal() {
    this.setData({
      modalName: "",
    })
  },
  // detail

  tabSelect(e) {
    let id = e.currentTarget.id;
    this.setData({
      tabCur: id,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    // console.log(app.globalData.user)

    let id = options.id || 1;
    let type = options.type || 1;
    if (options.scene) {
      id = decodeURIComponent(options.scene);
    }

    this.setData({
      ysId: id,
      ysType: type,
    })

    await this.getDetail(id, type)
  },

  /**
   * 
   */
  onUnload: function () {
    // if (rewardedVideoAd && rewardedVideoAd.destroy) {
    //   rewardedVideoAd.destroy()
    // }
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: async function () {
    wx.showLoading({
      title: '加载中...',
    })
    try {
      let that = this;
      if (that.data.nomore === true)
        return;

      let page = that.data.commentPage;
      let commentList = await api.getPostComments(page, that.data.post._id)
      if (commentList.data.length === 0) {
        that.setData({
          nomore: true
        })
        if (page === 1) {
          that.setData({
            nodata: true
          })
        }
      }
      else {
        that.setData({
          commentPage: page + 1,
          commentList: that.data.commentList.concat(commentList.data),
        })
      }
    }
    catch (err) {
      console.info(err)
    }
    finally {
      wx.hideLoading()
    }

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let share = this.data.shareData;
    let path = 'pages/detail/detail?id=' + share.id;
    let shareSet = {
      title: "邀请你参加" + share.title,
      path: '/pages/index/index?type=pageJump&path=' + encodeURIComponent(path),
      imageUrl: share.imageUrl,
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
        }
      },
    }
    return shareSet;
  },
  /**
   * 返回
   */
  navigateBack: function (e) {
    wx.switchTab({
      url: '../index/index'
    })
  },

  /**
   * 获取用户头像
   * @param {} e 
   */
  getUserInfo: function (e) {
    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo
      this.setData({
        showLogin: !this.data.showLogin,
        userInfo: e.detail.userInfo
      });
    } else {
      wx.switchTab({
        url: '../index/index'
      })
    }
  },
  /**
   * 获取文章详情
   */
  getDetail: async function (blogId) {
    wx.showLoading({
      title: '加载中...',
    })
    let that = this
    let postDetail = await api.getCompetitionDetail(blogId);
    let detail = postDetail.data;
    let shareData = {
      'title': detail.competition_name,
      'imageUrl': detail.image,
      'id': detail.id
    }
    that.setData({
      post: detail,
      shareData: shareData
    })
    wx.hideLoading()
  },
  /**
   * 显示隐藏功能
   */
  showMenuBox: function () {
    this.setData({
      isShow: !this.data.isShow
    })
  },
  /**
   * 收藏功能
   */
  postCollection: async function () {
    wx.showLoading({
      title: '加载中...',
    })
    try {
      let that = this;
      let collection = that.data.collection;
      if (collection.status === true) {
        let result = await api.deletePostCollectionOrZan(that.data.post._id, config.postRelatedType.COLLECTION)
        console.info(result)
        that.setData({
          collection: { status: false, text: "收藏", icon: "favor" }
        })
        wx.showToast({
          title: '已取消收藏',
          icon: 'success',
          duration: 1500
        })
      }
      else {
        let data = {
          postId: that.data.post._id,
          postTitle: that.data.post.title,
          postUrl: that.data.post.defaultImageUrl,
          postDigest: that.data.post.digest,
          type: config.postRelatedType.COLLECTION
        }
        await api.addPostCollection(data)
        that.setData({
          collection: { status: true, text: "已收藏", icon: "favorfill" }
        })

        wx.showToast({
          title: '已收藏',
          icon: 'success',
          duration: 1500
        })
      }
    }
    catch (err) {
      wx.showToast({
        title: '程序有一点点小异常，操作失败啦',
        icon: 'none',
        duration: 1500
      })
      console.info(err)
    }
    finally {
      wx.hideLoading()
    }

  },
  /**
   * 点赞功能
   */
  postZan: async function () {
    wx.showLoading({
      title: '加载中...',
    })
    try {
      let that = this;
      let zan = that.data.zan;
      if (zan.status === true) {
        let result = await api.deletePostCollectionOrZan(that.data.post._id, config.postRelatedType.ZAN)
        console.info(result)
        that.setData({
          zan: { status: false, text: "点赞", icon: "appreciate" }
        })
        wx.showToast({
          title: '已取消点赞',
          icon: 'success',
          duration: 1500
        })
      }
      else {
        let data = {
          postId: that.data.post._id,
          postTitle: that.data.post.title,
          postUrl: that.data.post.defaultImageUrl,
          postDigest: that.data.post.digest,
          type: config.postRelatedType.ZAN
        }
        await api.addPostZan(data)
        that.setData({
          zan: { status: true, text: "已赞", icon: "appreciatefill" }
        })

        wx.showToast({
          title: '已赞',
          icon: 'success',
          duration: 1500
        })
      }
    }
    catch (err) {
      wx.showToast({
        title: '程序有一点点小异常，操作失败啦',
        icon: 'none',
        duration: 1500
      })
      console.info(err)
    }
    finally {
      wx.hideLoading()
    }
  },
  /**
  * 展示打赏二维码
  * @param {} e 
  */
  showQrcode: async function (e) {
    wx.previewImage({
      urls: [config.moneyUrl],
      current: config.moneyUrl
    })
  },
  /**
   * 获取收藏和喜欢的状态
   */
  getPostRelated: async function (blogId) {
    let where = {
      postId: blogId,
      openId: app.globalData.openid
    }
    let postRelated = await api.getPostRelated(where, 1);
    let that = this;
    for (var item of postRelated.data) {
      if (config.postRelatedType.COLLECTION === item.type) {
        that.setData({
          collection: { status: true, text: "已收藏", icon: "favorfill" }
        })
        continue;
      }
      if (config.postRelatedType.ZAN === item.type) {
        that.setData({
          zan: { status: true, text: "已赞", icon: "appreciatefill" }
        })
        continue;
      }
    }
  },

  commentInput: function (e) {
    this.setData({
      commentContent: e.detail.value
    })
  },


  /**
 * 获取订阅消息
 */
  submitContent: async function (content, commentPage, accept) {
    let that = this
    let checkResult = await api.checkPostComment(content)
    if (!checkResult.result) {
      wx.showToast({
        title: '评论内容存在敏感信息',
        icon: 'none',
        duration: 2000
      })
      return
    }

    if (that.data.commentId === "") {
      var data = {
        postId: that.data.post._id,
        cNickName: that.data.userInfo.nickName,
        cAvatarUrl: that.data.userInfo.avatarUrl,
        cOpenId: app.globalData.openid,
        timestamp: new Date().getTime(),
        createDate: util.formatTime(new Date()),
        comment: content,
        childComment: [],
        flag: 1
      }
      await api.addPostComment(data, accept)
    }
    else {
      var childData = [{
        cOpenId: app.globalData.openid,
        cNickName: that.data.userInfo.nickName,
        cAvatarUrl: that.data.userInfo.avatarUrl,
        timestamp: new Date().getTime(), //new Date(),
        createDate: util.formatTime(new Date()),
        comment: content,
        tNickName: that.data.toName,
        tOpenId: that.data.toOpenId,
        flag: 1
      }]
      await api.addPostChildComment(that.data.commentId, that.data.post._id, childData, accept)
    }

    let commentList = await api.getPostComments(commentPage, that.data.post._id)
    if (commentList.data.length === 0) {
      that.setData({
        nomore: true
      })
      if (commentPage === 1) {
        that.setData({
          nodata: true
        })
      }
    }
    else {
      let post = that.data.post;
      post.totalComments = post.totalComments + 1
      that.setData({
        commentPage: commentPage + 1,
        commentList: commentList.data,
        commentContent: "",
        nomore: false,
        nodata: false,
        post: post,
        commentId: "",
        placeholder: "评论...",
        focus: false,
        toName: "",
        toOpenId: ""
      })
    }

    wx.showToast({
      title: '提交成功',
      icon: 'success',
      duration: 1500
    })
  },


  /**
   * 失去焦点时
   * @param {*} e 
   */
  onReplyBlur: function (e) {
    let that = this;
    const text = e.detail.value.trim();
    if (text === '') {
      that.setData({
        commentId: "",
        placeholder: "评论...",
        toName: ""
      });
    }
  },

  /**
   * towxml点击事件
   * @param {} e 
   */
  _tap: function (e) {
    console.info(e)
    try {
      if (e.target.dataset._el.attr.src != undefined) {
        wx.previewImage({
          urls: [e.target.dataset._el.attr.src],
        });
      }
    }
    catch (e) {
      console.info(e)
    }
  },
  adError(err) {
    console.log('Banner 广告加载失败', err)
    this.setData({
      showBanner: false
    })
  },
  adClose() {
    console.log('Banner 广告关闭')
    this.setData({
      showBanner: false
    })
  },

  /**
   * 阅读更多
   */
  // readMore: function () {
  //   let that = this;
  //   rewardedVideoAd.show()
  //     .catch(() => {
  //       rewardedVideoAd.load()
  //         .then(() => rewardedVideoAd.show())
  //         .catch(err => {
  //           console.log('激励视频 广告显示失败');
  //           that.setData({
  //             hideArticle: ''
  //           })
  //         })
  //     })
  // },
  //=======条件筛选
  changeForm: function (key, value) {
    let form = this.data.formData;
    form[key] = value
    this.setData({
      formData: form
    }, () => {
      //console.log(this.data.formData)
    })
  },
  changeSchool: function (option) {
    wx.navigateTo({
      url: '/pages/mine/edit_school/index',
    })
  },
  changeSkills: function (dom) {
    let type = dom.currentTarget.dataset.type || 'good';
    wx.navigateTo({
      url: '/pages/mine/edit_skills/index?type=' + type,
    })
  },
  changeProfessionType: function (opt) {
    this.changeForm('profession_type', this.data.professionType[opt.detail.value])
  },
  changeEducation: function (opt) {
    this.changeForm('education', this.data.education[opt.detail.value])
  },
  changeGrade: function (opt) {
    this.changeForm('grade', this.data.grade[opt.detail.value])
  },
  changeProvince: function (opt) {
    this.changeForm('province', this.data.province[opt.detail.value])
  },
  changeNumMIn: function (opt) {
    this.changeForm('numMin', opt.detail.value)
  },
  changeNumMax: function (opt) {
    this.changeForm('maxNum', opt.detail.value)
  },
  //点击确定
  sureModal: function () {
    console.log(this.data.modalName, '====');
    let param = this.data.formData;
    console.log(param);
    //findStuModel, 
    //createTeamModel
    //findTeamModel
    switch (this.data.modalName) {
      case "createTeamModel":
        const user = app.globalData.user
        if (user.register == "no") {
          toast.alert("清先注册")
          return
        }
        this.onCreateTeam()
        break
    }
  }
})